package com.qingcheng.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.*;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.goods.*;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.goods.SpuService;
import com.qingcheng.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SpuService.class)
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    @Autowired
    private GoodslogMapper goodslogMapper;

    @Autowired
    private SkuService skuService;
    /**
     * 返回全部记录
     * @return
     */
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 分页查询
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Spu> findPage(int page, int size) {
        PageHelper.startPage(page,size);
        Page<Spu> spus = (Page<Spu>) spuMapper.selectAll();
        return new PageResult<Spu>(spus.getTotal(),spus.getResult());
    }

    /**
     * 条件查询
     * @param searchMap 查询条件
     * @return
     */
    public List<Spu> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return spuMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Spu> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        Page<Spu> spus = (Page<Spu>) spuMapper.selectByExample(example);
        return new PageResult<Spu>(spus.getTotal(),spus.getResult());
    }

    /**
     * 根据Id查询
     * @param id
     * @return
     */
    public Spu findById(String id) {
        return spuMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增
     * @param spu
     */
    public void add(Spu spu) {
        spuMapper.insert(spu);
        //根据spuId查询所有sku
        Example example=new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",spu.getId());
        List<Sku> skuList = skuMapper.selectByExample(example);
        if(skuList.size()!=0){
            for (Sku sku : skuList) {
                skuService.updatePriceToRedis(sku.getId(),sku.getPrice());
            }
        }
    }

    /**
     * 修改
     * @param spu
     */
    public void update(Spu spu) {
        spuMapper.updateByPrimaryKeySelective(spu);
        Example example=new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",spu.getId());
        List<Sku> skuList = skuMapper.selectByExample(example);
        if(skuList.size()!=0){
            for (Sku sku : skuList) {
                skuService.updatePriceToRedis(sku.getId(),sku.getPrice());
            }
        }
    }

    /**
     *  删除
     * @param id
     */
    public void delete(String id) {
        spuMapper.deleteByPrimaryKey(id);
        Example example=new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",id);
        List<Sku> skuList = skuMapper.selectByExample(example);
        if(skuList.size()!=0){
            for (Sku sku : skuList) {
                skuService.deletePriceFromRedis(sku.getId());
            }
        }
    }

    /**
     * 定义保存spu和sku数据的方法，直接保存Spu,遍历保存Sku
     * @param goods
     */
    @Override
    @Transactional
    public void saveGoods(Goods goods) {
        Goodslog goodslog=new Goodslog();
        //获取Spu对象，给sup对象赋值保存
        Spu spu = goods.getSpu();
        long spuId=0;
        //因为添加和修改是一个方法，应当判断是何方法
        if(spu.getId()==null){//此时是添加用户
            //雪花算法获取Spu的Id值
            spuId = idWorker.nextId();
            spu.setId(spuId+"");   //设置Id
            spu.setSaleNum(0);      //设置销量
            spu.setCommentNum(0);     //设置评论数
            spu.setIsMarketable("0");    //设置是否上架
            spu.setIsEnableSpec("0");     //设置是否启用规格
            spu.setIsDelete("0");     //设置是否删除
            spu.setStatus("0");   //设置商品状态
            //保存Spu对象
            spuMapper.insertSelective(spu);
            //保存新增的商品日志信息
            goodslog.setSpuId(spuId+"");
            //设置日志信息
            goodslog.setMessage("商品新增");
        }else {     //此时是修改方法
            //给spuId赋值
            spuId=Long.parseLong(spu.getId());
            //删除已经存在的sku
            Example example=new Example(Sku.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("spuId",spu.getId());
            skuMapper.deleteByExample(example);
            //修改Spu数据
            spuMapper.updateByPrimaryKeySelective(spu);
            //保存修改的商品日志信息
            goodslog.setSpuId(spu.getId());
            //设置日志信息
            goodslog.setMessage("商品修改");

        }
        //统一设置所有Sku创建时间,创建时间
        Date nowTime=new Date();


        //获取spu的Category三级目录的名称
        String categoryName = categoryMapper.selectByPrimaryKey(spu.getCategory3Id()).getName();
        //获取spu的Brand名称
        String brandName = brandMapper.selectByPrimaryKey(spu.getBrandId()).getName();

        //判断如果是新增sku：
            //设置id 、name等属性
        //判断如果是修改sku(已删除所有的sku)：
            //id、createTime不用设置  name、updateTime等需要重新设置

        //遍历集合
        List<Sku> skuList = goods.getSkuList();
        for (Sku sku : skuList) {
            String skuId = sku.getId();
            if(skuId==null || "".equals(skuId)){ //此时是增加
                //设置sku对象的Id
                sku.setCreateTime(nowTime); //设置创建时间
                sku.setId(idWorker.nextId()+"");
                sku.setSaleNum(0);  //设置销量
                sku.setCommentNum(0); //设置评论数
            }
            //增强程序健壮性，商品spec规格可能为空，此时sku名字就是spu的名字
            if(sku.getSpec()==null || "".equals(sku.getSpec())){
                sku.setSpec("{}");
            }

            //设置sku的name属性，名字格式=spu名+sku的规格集合每一项
            String specName=spu.getName();
            String spec = sku.getSpec(); //获取规格字符串 {"颜色":"红色","大小":"5寸"}
            Map<String,String> map = JSON.parseObject(spec, Map.class); //将字符串转回Map集合
            for(String value:map.values()){
                specName+=" "+value;     //拼接字符串，是sku名称是spu名+规格
            }
            sku.setName(specName);   //设置sku名称
            sku.setUpdateTime(nowTime);  //设置更新时间
            sku.setSpuId(spuId+"");      //设置sku的spuId
            sku.setCategoryId(spu.getCategory3Id());  //设置三级目录的id为sku的category的Id
            sku.setCategoryName(categoryName);    //设置三级目录的名称，根据是数据库查询
            sku.setBrandName(brandName);    //设置品牌名
            skuMapper.insertSelective(sku);
        }


        //设置日志时间信息
        goodslog.setUpdateTime(nowTime);
        //设置日志提交人
        goodslog.setManager("商鞅");
        //保存日志信息
        goodslogMapper.insert(goodslog);

        //建立分类表和品牌表的关系
        //查询关系在数据库中是否存在
        CategoryBrand categoryBrand=new CategoryBrand();
        categoryBrand.setBrandId(spu.getBrandId());
        categoryBrand.setCategoryId(spu.getCategory3Id());
        int count = categoryBrandMapper.selectCount(categoryBrand);
        if(count==0){
            categoryBrandMapper.insert(categoryBrand);
        }

        //遍历循环Goods中的SkuList

      /*  for(Sku sku:skuList){
            //设置sku对象的Id
            sku.setId(idWorker.nextId()+"");
            //设置sku的name属性，名字格式=spu名+sku的规格集合每一项
            String specName=spu.getName();
            String spec = sku.getSpec(); //获取规格字符串 {"颜色":"红色","大小":"5寸"}
            Map<String,String> map = JSON.parseObject(spec, Map.class); //将字符串转回Map集合
            for(String value:map.values()){
                specName+=" "+value;     //拼接字符串，是sku名称是spu名+规格
            }
            sku.setName(specName);   //设置sku名称
            sku.setCreateTime(createTime); //设置创建时间
            sku.setUpdateTime(updateTime);  //设置更新时间
            sku.setSpuId(spuId+"");      //设置sku的spuId
            sku.setCategoryId(spu.getCategory3Id());  //设置三级目录的id为sku的category的Id
            sku.setCategoryName(categoryName);    //设置三级目录的名称，根据是数据库查询
            sku.setBrandName(brandName);    //设置品牌名
            sku.setSaleNum(0);  //设置销量
            sku.setCommentNum(0); //设置评论数

            //保存sku数据
            skuMapper.insertSelective(sku);
*/
    }

    /**
     * 根据Id查询对应的商品以及Sku
     * @param id
     * @return
     */
    @Override
    public Goods findGoodsById(String id) {
        Goods goods=new Goods();
        //根据Id查询Spu对象
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //获取Sku对应的List集合
        Example example=new Example(Sku.class);  //获取Example对象
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",id);
        List<Sku> skuLsit = skuMapper.selectByExample(example);
        //封装goods对象
        goods.setSpu(spu);
        goods.setSkuList(skuLsit);
        return goods;
    }

    /**
     * 定义审核方法
     * @param id 审核对象的id
     * @param status 审核的状态
     * @param message  审核信息的记录
     * @param auditer   审核人
     */
    @Override
    @Transactional
    public void audit(String id, String status, String message, String auditer) {
        //创建日志对象
        Goodslog goodslog=new Goodslog();
        goodslog.setUpdateTime(new Date());
        goodslog.setSpuId(id);
        goodslog.setManager("商鞅");

        //修改对象状态
        Spu spu=new Spu();
        spu.setId(id);
        spu.setStatus(status);
        if("1".equals(status)){//审核通过，直接上架
            spu.setIsMarketable("1");
            goodslog.setMessage("商品审核：通过，自动上架");
        }else if("2".equals(status)){
            goodslog.setMessage("商品审核未通过");
        }else{
            goodslog.setManager("商品审核未通过，已删除");
        }
        spuMapper.updateByPrimaryKeySelective(spu);
        goodslogMapper.insert(goodslog);
        //添加审核日志:修改状态，审核时间，审核人
        //添加商品日志
    }

    /**
     * 定义商品下架的方法
     * @param id
     */
    @Override
    @Transactional
    public void pull(String id) {
        //商品下架
        Spu spu=new Spu();
        spu.setId(id);
        spu.setIsMarketable("0");
        spuMapper.updateByPrimaryKeySelective(spu);
        //记录商品日志
        Goodslog goodslog=new Goodslog();
        goodslog.setMessage("商品下架");
        goodslog.setUpdateTime(new Date());
        goodslog.setSpuId(id);
        goodslog.setManager("商鞅");
        goodslogMapper.insert(goodslog);
    }

    /**
     * 定义商品上架的方法
     * @param id
     */
    @Override
    @Transactional
    public void put(String id) {
        //创建日志对象
        Goodslog goodslog=new Goodslog();
        goodslog.setUpdateTime(new Date());
        goodslog.setSpuId(id);
        goodslog.setManager("商鞅");
        //查看审核状态
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if(!"1".equals(spu.getStatus())){
            goodslog.setMessage("商品上架失败，审核未通过");
            goodslogMapper.insert(goodslog);
            throw new RuntimeException("商品未通过审核");
        }
        spu.setIsMarketable("1");
        spuMapper.updateByPrimaryKeySelective(spu);
        //记录商品日志
        goodslog.setMessage("商品上架");
        goodslogMapper.insert(goodslog);
    }

    /**
     * 定义批量上架的方法
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public int putMany(String[] ids) {
        Spu spu=new Spu();
        spu.setIsMarketable("1");
        Example example=new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        //sql语句 ： update tb_spu set status = 1  where id in ( 1,3,4) and isMarketable=0 and status=1
        criteria.andIn("id", Arrays.asList(ids));
        //判断是否上架
        criteria.andEqualTo("isMarketable","0");
        //判断审核通过
        criteria.andEqualTo("status",1);
        return spuMapper.updateByExampleSelective(spu,example);
    }

    /**
     * 定义批量下架的方法
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public int pullMany(String[] ids) {
        Spu spu=new Spu();
        spu.setIsMarketable("0");
        Example example=new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id",Arrays.asList(ids));
        criteria.andEqualTo("isMarketable",1);
        return spuMapper.updateByExampleSelective(spu,example);
    }

    /**
     * 定义逻辑删除的方法
     * @param id
     */
    @Override
    @Transactional
    public void delFake(String id) {
        Goodslog goodslog=new Goodslog();
        goodslog.setMessage("商品删除");
        goodslog.setUpdateTime(new Date());
        goodslog.setSpuId(id);
        goodslog.setManager("商鞅");
        goodslogMapper.insert(goodslog);
        Spu spu=new Spu();
        spu.setId(id);
        spu.setIsDelete("1");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 定义删除还原的方法
     * @param id
     */
    @Override
    @Transactional
    public void returnDel(String id) {
        Goodslog goodslog=new Goodslog();
        goodslog.setMessage("商品还原");
        goodslog.setUpdateTime(new Date());
        goodslog.setSpuId(id);
        goodslog.setManager("商鞅");
        goodslogMapper.insert(goodslog);
        Spu spu=new Spu();
        spu.setId(id);
        spu.setIsDelete("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }


    /**
     * 构建查询条件
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 主键
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andLike("id","%"+searchMap.get("id")+"%");
            }
            // 货号
            if(searchMap.get("sn")!=null && !"".equals(searchMap.get("sn"))){
                criteria.andLike("sn","%"+searchMap.get("sn")+"%");
            }
            // SPU名
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name"))){
                criteria.andLike("name","%"+searchMap.get("name")+"%");
            }
            // 副标题
            if(searchMap.get("caption")!=null && !"".equals(searchMap.get("caption"))){
                criteria.andLike("caption","%"+searchMap.get("caption")+"%");
            }
            // 图片
            if(searchMap.get("image")!=null && !"".equals(searchMap.get("image"))){
                criteria.andLike("image","%"+searchMap.get("image")+"%");
            }
            // 图片列表
            if(searchMap.get("images")!=null && !"".equals(searchMap.get("images"))){
                criteria.andLike("images","%"+searchMap.get("images")+"%");
            }
            // 售后服务
            if(searchMap.get("saleService")!=null && !"".equals(searchMap.get("saleService"))){
                criteria.andLike("saleService","%"+searchMap.get("saleService")+"%");
            }
            // 介绍
            if(searchMap.get("introduction")!=null && !"".equals(searchMap.get("introduction"))){
                criteria.andLike("introduction","%"+searchMap.get("introduction")+"%");
            }
            // 规格列表
            if(searchMap.get("specItems")!=null && !"".equals(searchMap.get("specItems"))){
                criteria.andLike("specItems","%"+searchMap.get("specItems")+"%");
            }
            // 参数列表
            if(searchMap.get("paraItems")!=null && !"".equals(searchMap.get("paraItems"))){
                criteria.andLike("paraItems","%"+searchMap.get("paraItems")+"%");
            }
            // 是否上架
            if(searchMap.get("isMarketable")!=null && !"".equals(searchMap.get("isMarketable"))){
                criteria.andLike("isMarketable","%"+searchMap.get("isMarketable")+"%");
            }
            // 是否启用规格
            if(searchMap.get("isEnableSpec")!=null && !"".equals(searchMap.get("isEnableSpec"))){
                criteria.andLike("isEnableSpec","%"+searchMap.get("isEnableSpec")+"%");
            }
            // 是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                criteria.andLike("isDelete","%"+searchMap.get("isDelete")+"%");
            }
            // 审核状态
            if(searchMap.get("status")!=null && !"".equals(searchMap.get("status"))){
                criteria.andLike("status","%"+searchMap.get("status")+"%");
            }

            // 品牌ID
            if(searchMap.get("brandId")!=null ){
                criteria.andEqualTo("brandId",searchMap.get("brandId"));
            }
            // 一级分类
            if(searchMap.get("category1Id")!=null ){
                criteria.andEqualTo("category1Id",searchMap.get("category1Id"));
            }
            // 二级分类
            if(searchMap.get("category2Id")!=null ){
                criteria.andEqualTo("category2Id",searchMap.get("category2Id"));
            }
            // 三级分类
            if(searchMap.get("category3Id")!=null ){
                criteria.andEqualTo("category3Id",searchMap.get("category3Id"));
            }
            // 模板ID
            if(searchMap.get("templateId")!=null ){
                criteria.andEqualTo("templateId",searchMap.get("templateId"));
            }
            // 运费模板id
            if(searchMap.get("freightId")!=null ){
                criteria.andEqualTo("freightId",searchMap.get("freightId"));
            }
            // 销量
            if(searchMap.get("saleNum")!=null ){
                criteria.andEqualTo("saleNum",searchMap.get("saleNum"));
            }
            // 评论数
            if(searchMap.get("commentNum")!=null ){
                criteria.andEqualTo("commentNum",searchMap.get("commentNum"));
            }

        }
        return example;
    }

}
